#!/bin/sh
set -u

# Description: Update nnn plugins to installed nnn version
#
# This is modified version of the nnn's script 'getplugs' for installing
# plugins from /usr/share/nnn/plugins.
#
# Shell: POSIX compliant

SHARED_PLUGIN_DIR=/usr/share/nnn/plugins
CONFIG_DIR=${XDG_CONFIG_HOME:-$HOME/.config}/nnn/
PLUGIN_DIR=${CONFIG_DIR}plugins

merge() {
	if which nvim >/dev/null 2>&1; then
		nvim -d "$1" "$2"
	else
		vimdiff +0 "$1" "$2"
	fi
}

prompt() {
	printf "%s\n" "Plugin $1 already exists and is different."
	printf "Keep (k), merge (m), overwrite (o) [default: k]? "
	read -r operation
}


if [ $# -gt 0 ]; then
	cat >&2 <<-EOF
	Usage: $0

	Update nnn plugins in $PLUGIN_DIR to installed nnn version
	EOF
	exit 1
fi

[ -d "$SHARED_PLUGIN_DIR" ] || exit 1

# Backup any earlier plugins.
if [ -d "$PLUGIN_DIR" ]; then
	tar -C "$CONFIG_DIR" -czf "$CONFIG_DIR""plugins-$(date '+%Y%m%d%H%M').tar.gz" plugins/ || exit 1
fi

mkdir -p "$PLUGIN_DIR" || exit 1

for path in $(find "$SHARED_PLUGIN_DIR" -mindepth 1 -maxdepth 1); do
	name=$(basename "$path")
	if [ -f "$PLUGIN_DIR/$name" ]; then
		if ! diff -q "$path" "$PLUGIN_DIR/$name" >/dev/null; then
			prompt "$name"
			case "$operation" in
				m) merge "$path" "$PLUGIN_DIR"/
				   chmod +x "$PLUGIN_DIR/$name";;

				o) rm "$PLUGIN_DIR/$name"
				   ln -sv "$path" "$PLUGIN_DIR/$name";;
			esac
		fi
	else
		ln -sv "$path" "$PLUGIN_DIR/$name"
	fi
done
